package org.linlinjava.litemall.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.linlinjava.litemall.admin.dto.AdminPosAdDTO;
import org.linlinjava.litemall.core.fileenum.FileEnum;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallAdminMapper;
import org.linlinjava.litemall.db.dao.LitemallShopMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.PageTools;
import org.linlinjava.litemall.db.vo.LitemallPosAdAllsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理pos广告服务
 *
 * @author imuamacmini
 * @date 2023/01/10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminPosAdService extends ResponseUtil {

    @Value("${file.linuxPath}")
    private String linuxPath;

    //当前项目的上一级目录
    private String mypath;

    //文件名
    private String fileName;

    //要创建文件目录
    private File createMkdirs=null;

    //要创建文件
    private File filePath=null;

    /**
     * litemall pos广告服务
     */
    private final LitemallPosAdService litemallPosAdService;

    /**
     * litemall管理服务
     */
    private final LitemallAdminService litemallAdminService;

    private final LitemallAdminMapper litemallAdminMapper;

    private final LitemallShopService litemallShopService;

    private final LitemallShopMapper litemallShopMapper;

    private final LitemallStorageService litemallStorageService;
    private final FileStorageService fileStorageService;
    private final LitemallRoleService litemallRoleService;

    /**
     * pos广告上传
     *
     * @param adminPosAdDTO 管理pos广告dto
     * @param adminId       管理员id
     * @return {@link Response}
     */
    public Response PosAdUploader(AdminPosAdDTO adminPosAdDTO, Integer adminId) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        LitemallPosAd litemallPosAd = LitemallPosAd.builder()
                .id(snowflake.nextId())
                .addTime(LocalDateTime.now())
                .uploaderId(adminId)
                .uploaderName(litemallAdminService.findById(adminId).getUsername())
                .deleted(0)
                .build();
        BeanUtils.copyProperties(adminPosAdDTO,litemallPosAd);
        return ResponseUtil.ok(litemallPosAdService.save(litemallPosAd));
    }

    /**
     * pos广告更新
     *
     * @param adminPosAdDTO litemall pos广告
     * @return {@link Response}
     */
    public Response PosAdUpdate(AdminPosAdDTO adminPosAdDTO) {
        LitemallPosAd litemallPosAd = LitemallPosAd.builder()
                .updateTime(LocalDateTime.now())
                .build();
        BeanUtils.copyProperties(adminPosAdDTO,litemallPosAd);
        return ResponseUtil.ok(litemallPosAdService.updateById(litemallPosAd));
    }

    /**
     * pos广告搜索所有
     *
     * @param page    页面
     * @param limit   限制
     * @param shopId  商店id
     * @param adminId 管理员id
     * @return {@link Response}
     */
    public Response PosAdSearchAll(Integer page, Integer limit, Integer shopId, Integer adminId) {

        List<LitemallPosAd> adSearchAll = litemallPosAdService.PosAdSearchAll(shopId,adminId).stream()
                .map(posAd->{
                    LitemallPosAdAllsVO litemallPosAdAllsVO =new  LitemallPosAdAllsVO();
                    litemallPosAdAllsVO.setImgObjs(Arrays.asList(posAd.getImgObj()).stream().map(imgObjId -> litemallStorageService.findById(imgObjId)).collect(Collectors.toList()));
                    litemallPosAdAllsVO.setStaleDated(LocalDateTime.now().isAfter(posAd.getStartTime()) && LocalDateTime.now().isBefore(posAd.getEndTime()));
                    BeanUtils.copyProperties(posAd,litemallPosAdAllsVO);
                    return litemallPosAdAllsVO;
                })
                .collect(Collectors.toList());
        PageTools pageTools = PageTools.builder().build();
        pageTools.pageTools(page,limit,adSearchAll);
        return ResponseUtil.ok(pageTools);
    }

    /**
     * pos广告细节
     *
     * @param posAdId pos广告标识
     * @return {@link Response}
     */
    public Response PosAdDetails(Long posAdId) {
        return ResponseUtil.ok(litemallPosAdService.getById(posAdId));
    }

    /**
     * pos广告删除
     *
     * @param posAds pos广告
     * @return {@link Response}
     */
    public Response PosAdDeleted(Long[] posAds) {
        return ResponseUtil.ok(litemallPosAdService.removeBatchByIds(Arrays.asList(posAds)));
    }

    /**
     * pos广告管理用户
     *
     * @return {@link Response}
     */
    public Response posAdAdminUserS() {
        return ResponseUtil.ok(litemallAdminService.all());
    }

    @SneakyThrows
    public Response posAdvanced(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();//获取文件的名称
        String fileSuffix= FileUtil.extName(originalFilename).toLowerCase();

        switch (fileSuffix){
            case FileEnum.JPG:
                fileName=System.currentTimeMillis()+"."+FileEnum.JPG;
                break;
            case FileEnum.PNG:
                fileName=System.currentTimeMillis()+"."+FileEnum.PNG;
                break;
            case FileEnum.JPEG:
                fileName=System.currentTimeMillis()+"."+FileEnum.JPEG;
                break;
            case FileEnum.GIF:
                fileName=System.currentTimeMillis()+"."+FileEnum.GIF;
                break;
            case FileEnum.MP4:
                fileName=System.currentTimeMillis()+"."+FileEnum.MP4;
                break;
            default: return ResponseUtil.fail(400,"文件格式不对！");
        }
        //获取当前系统
        String os=System.getProperty("os.name");
        if (os.toLowerCase().startsWith("Linux")&&!StrUtil.isEmpty(linuxPath)) {  //windows系统
            //如果是linux环境下，放在固定路径
            log.info("获取的linux位置{}"+linuxPath);
            mypath =linuxPath;
        }else{
            mypath = System.getProperty("user.dir")+"/upload-files/";
        }
        mypath+= UUID.randomUUID();
        log.info(mypath);
        String finalName=mypath+"/"+fileName;
        log.info("文件完全路径 =:{} " + finalName);
        //如果没有该文件目录，则创建
        createMkdirs =new File(mypath);
        if(!createMkdirs.exists()){
            createMkdirs.mkdirs();
        }
        filePath=new File(finalName);
        if(!filePath.exists()){
            filePath.createNewFile();
        }
        //将文件写入磁盘
        file.transferTo(filePath);
        return ResponseUtil.ok(filePath);
    }

    public Response posAdMiniio(MultipartFile file) {
        FileInfo fileInfo = fileStorageService.of(file)
                .upload();
        //上传的原图
        LitemallStorage storageOriginalInfo = new LitemallStorage();
        storageOriginalInfo.setName(fileInfo.getOriginalFilename());
        String s = String.valueOf(fileInfo.getSize());
        storageOriginalInfo.setSize(Integer.valueOf(s));
        storageOriginalInfo.setType(fileInfo.getContentType());
        storageOriginalInfo.setKey(fileInfo.getFilename());
        storageOriginalInfo.setUrl(fileInfo.getUrl());
        storageOriginalInfo.setAddTime(LocalDateTime.now());
        storageOriginalInfo.setUpdateTime(LocalDateTime.now());
        storageOriginalInfo.setDeleted(false);
        //批量存储
        litemallStorageService.save(storageOriginalInfo);
        return fileInfo == null?fail("上传失败！"):success(storageOriginalInfo);
    }

    public Response posAdShopS(List<Integer> shopIds) {
        return ResponseUtil.ok(litemallShopService.getByIds(shopIds));
    }

    public Response posAdImgObjS(List<Integer> adImgObjS) {
        List<LitemallStorage> litemallStorages = adImgObjS.stream()
                .map(adImgObj -> litemallStorageService.findById(adImgObj))
                .collect(Collectors.toList());
        return ResponseUtil.ok(litemallStorages);
    }

    public Response posAdAdminS(Integer adminId) {
        LitemallAdmin litemallAdmin = litemallAdminService.findById(adminId);
        List<LitemallAdmin> litemallAdmins = CollUtil.newArrayList();
        //要确定权限再做修改
        switch (litemallAdmin.getRoleIds()[0]){
            case 1:
                litemallAdmins = litemallAdminMapper.selectList(null);
                break;
            default:
                litemallAdmins = litemallAdminMapper.selectList(Wrappers.lambdaQuery(LitemallAdmin.class)
                        .eq(LitemallAdmin::getShopId, litemallAdmin.getShopId())
                );
                break;
        }
        return ResponseUtil.ok(litemallAdmins);
    }

    public Response posAdShopOptionS(Integer adminId) {
        LitemallAdmin litemallAdmin = litemallAdminService.findById(adminId);
        List<LitemallShop> litemallShops = CollUtil.newArrayList();
        //要确定权限再做修改
        switch (litemallAdmin.getRoleIds()[0]){
            case 1:
                litemallShops = litemallShopService.all();
                break;
            default:
                litemallShops = litemallShopMapper.selectList(Wrappers.lambdaQuery(LitemallShop.class)
                        .eq(LitemallShop::getId,litemallAdmin.getShopId())
                );
                break;
        }
        return ResponseUtil.ok(litemallShops);
    }
}
